package com.jieshuibao.service;

import java.util.Date;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.jieshuibao.common.res.BaseRes;
import com.jieshuibao.mapper.CardBatchExMapper;
import com.jieshuibao.mapper.CardBatchMapper;
import com.jieshuibao.model.db.CardBatch;
import com.jieshuibao.model.db.RedEnvelopes;
import com.jieshuibao.util.DateUtils;
import com.jieshuibao.util.PayTypeUtil;

@Service
public class CardBatchService {
	@Resource
	private CardBatchExMapper cardBatchExMapper;
	@Resource
	private CardBatchMapper cardBatchMapper;
	@Resource
	private RedEnvelopesService redEnvelopesService;
	/**
	 * 更新电子版问答卡激活次数
	 * @param userId 用户主键
	 * @param cardId 问答卡主键
	 */
	public BaseRes<String> bindingElectronicQACard(String userId,Long cardBatchId) {
		BaseRes<String> baseRes = new BaseRes<String>();
		baseRes = this.checkElectronicQACard(cardBatchId);
		if(!"1".equals(baseRes.getCode())){
			return baseRes;
		}
		CardBatch cardBatch = cardBatchMapper.selectByPrimaryKey(cardBatchId);
		Double amount = cardBatch.getAmount();//金额
		Long channelId = cardBatch.getChannelId();//渠道ID
		//对当前用户绑定固定面值问答红卡
		RedEnvelopes redEnvelopes = new RedEnvelopes();
		redEnvelopes.setMoney(cardBatch.getAmount());//金额
		redEnvelopes.setUserPhoneNum(userId);//领取红包人的用户主键
		redEnvelopes.setRedType(PayTypeUtil.REDENVELPES_BINDINGQACARD);//红包类型
		/**
		 * 1.将问答卡金额赋值增加到用户问答余额
		 * 2.将问答卡渠道绑定到用户
		 * 3.交易流水
		 */ 
		redEnvelopesService.addQACardRedEnvelopes(redEnvelopes,channelId);
		int result = cardBatchExMapper.updateActivedCountByPrimaryKey(cardBatchId);
		if(result != 1){
			//渠道ID为空
			baseRes.setCode("0");
			baseRes.setDes("数据错误");
			return baseRes;
		}
		baseRes.setAmount(amount);
		baseRes.setCode("1");
		baseRes.setDes("绑定成功");
		return baseRes;
	}
	/**
	 * 校验电子版问答卡是否可用
	 * @param userId 用户主键
	 * @param cardId 问答卡主键
	 */
	public BaseRes<String> checkElectronicQACard(Long cardBatchId) {
		BaseRes<String> baseRes = new BaseRes<String>();
		CardBatch cardBatch = cardBatchMapper.selectByPrimaryKey(cardBatchId);
		if(cardBatch == null){
			//查不到电子问答卡
			baseRes.setCode("0");
			baseRes.setDes("问答卡不存在");
			return baseRes;
		}
		Double amount = cardBatch.getAmount();//金额
		Date limitActiveTime = cardBatch.getLimitActiveTime();//激活截止日期
		if(amount <= 0){
			baseRes.setCode("0");
			baseRes.setDes("此问答卡金额错误");
			return baseRes;
		}
		Date nowDate = new Date();
		if(DateUtils.compareDateYMD(nowDate, limitActiveTime)){
			//激活截止日期小于当前时间
			baseRes.setCode("0");
			baseRes.setDes("此问答卡已过期");
			return baseRes;
		}
		if(cardBatch.getActivedCount() >= cardBatch.getNum()){
			//渠道ID为空
			baseRes.setCode("0");
			baseRes.setDes("已达到激活数量，无法使用");
			return baseRes;
		}
		baseRes.setCode("1");
		return baseRes;
	}
}
